import { useCallback, useContext, useLayoutEffect, useRef, useSyncExternalStore } from "react";
import { ReactReduxContext } from "react-redux";
import { shallowEqual } from "react-redux";


export const useSelector = (selector: any, equalityFn = shallowEqual) => {
  const { store } = useContext(ReactReduxContext);
  const { subscribe, getState } = store;

  const selectorRef = useRef(selector);
  useLayoutEffect(() => {
    selectorRef.current = selector;
  }, [selector]);

  const lastSelectedStateRef = useRef(null);

  const thisSubscribe = useCallback((setState: () => void) => {
    return subscribe(() => {
      const currentState = selectorRef.current(getState());
      if (!equalityFn(currentState, lastSelectedStateRef.current)) {
        setState();
      }
    })
  }, [equalityFn, getState, subscribe]);


  const state = useSyncExternalStore(thisSubscribe, getState);
  lastSelectedStateRef.current = selectorRef.current(state)
  return lastSelectedStateRef.current;
};